//
//  InstagramViewController.m
//  Bespoke
//
//  Created by Cheng on 12/8/27.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "InstagramViewController.h"
#import "AppDelegate.h"

#define AUTHORIZEAPI @"https://api.instagram.com/oauth/authorize/"
#define TOKENAPI @"https://api.instagram.com/oauth/access_token/"
#define CLIENTID @"72a58604b29c40fbac41ac1cb8aea560"
#define CLIENTSECRET @"46e8535dc9bf40d2b20d297721e2cae4"
#define REDIRECTURI @"http://54.235.166.43/BeSpokeAPI/Instagram/"
#define SCOPE @"comments+relationships+likes"

@interface InstagramViewController ()

@end

@implementation InstagramViewController
@synthesize webView,ActivityView, BK_En_object;
@synthesize delegate;

-(IBAction)close:(id)sender
{
    [self.delegate InstagramViewControllerDelegateDidClose:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    [ActivityView setColor:[UIColor blackColor]];
    webView.delegate = self;
    NSString *fullAuthUrlString = [[NSString alloc]
                                   initWithFormat:@"%@?client_id=%@&redirect_uri=%@&scope=%@&response_type=token&display=touch",
                                   AUTHORIZEAPI,
                                   CLIENTID,
                                   REDIRECTURI,
                                   SCOPE
                                   ];
    NSURL *authUrl = [NSURL URLWithString:fullAuthUrlString];
    NSURLRequest *myRequest = [[NSURLRequest alloc] initWithURL:authUrl];
    [webView loadRequest:myRequest];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

// GRAB THE URL TRAFFIC TO CATCH THE ACCESS TOKEN OUT OF THE RETURN URL
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSURL *Url = [request URL];
    NSArray *UrlParts = [Url pathComponents];
    if ([[UrlParts objectAtIndex:(1)] isEqualToString:@"BeSpokeAPI"]) {
        // CONVERT TO STRING AN CLEAN
        NSString *urlResources = [Url resourceSpecifier];
        urlResources = [urlResources stringByReplacingOccurrencesOfString:@"?" withString:@""];
        urlResources = [urlResources stringByReplacingOccurrencesOfString:@"#" withString:@""];
        
        // SEPORATE OUT THE URL ON THE /
        NSArray *urlResourcesArray = [urlResources componentsSeparatedByString:@"/"];
        // THE LAST OBJECT IN THE ARRAY
        NSString *urlParamaters = [urlResourcesArray objectAtIndex:([urlResourcesArray count]-1)];
        // SEPORATE OUT THE URL ON THE &
        NSArray *urlParamatersArray = [urlParamaters componentsSeparatedByString:@"&"];
        
        if([urlParamatersArray count] == 1) {
            NSString *keyValue = [urlParamatersArray objectAtIndex:(0)];
            NSArray *keyValueArray = [keyValue componentsSeparatedByString:@"="];
            
            if([[keyValueArray objectAtIndex:(0)] isEqualToString:@"access_token"]) {
                // THE TOKEN IS NOW IN [keyValueArray objectAtIndex:(1)]
                NSLog(@"Instagram_access_token:%@",[keyValueArray objectAtIndex:(1)]);
                
                [BK_En_object setAccountInfoInstagram:[keyValueArray objectAtIndex:(1)]];
                [BK_En_object setInstagramONorOff:YES];
                
                [self.delegate InstagramViewControllerDelegateDidClose:self];
                return YES;
            }
        }
        else {
            // THERE WAS AN ERROR
        }
        
        [self.delegate InstagramViewControllerDelegateDidClose:self];
        return NO;
    }
    return YES;
}

#pragma mark - Interface Orientation Management

//For iOS 5
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight));
}

//For iOS 6
-(BOOL)shouldAutorotate {
    return YES;
}

-(NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

#pragma mark - UIWebViewDelegate

- (void)webViewDidStartLoad:(UIWebView *)webView{
    ActivityView.hidden = NO;
    [ActivityView startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    ActivityView.hidden = YES;
    [ActivityView stopAnimating];
}

@end
